import { useEffect, useState } from "react";
/**
 * 
 * @param {fn} 
 */
export default function useFetchList({ API }) {
  const [filterParams, setFilterParams] = useState({
    page: 1,
    size: 3,
    sort: "desc",
    order: "createTime",
  });

  const [dataSource, setDataSource] = useState([]);

  const [total, setTotal] = useState(0);

  /**
   * 过滤参数发生改变
   * 重新调用接口
   */
  useEffect(() => {
    getData();
  }, [filterParams]);

  /**
   * 获取数据
   */
  const getData = async () => {
    const data = await API(filterParams);

    // 添加key
    data.list.forEach((item) => {
      item.key = item.id;
    });

    setDataSource(data.list);
    setTotal(data.pagination.total);
  };

  return {
    dataSource,
    total,
    setFilterParams,
    getData,
    filterParams
  };
}
